package com.wh.basic.utils;

import com.wh.basic.jwt.JwtTokenUtils;
import com.wh.basic.jwt.LoginData;
import com.wh.basic.jwt.Payload;
import com.wh.basic.jwt.RsaUtils;
import com.wh.user.pojo.LoginInfo;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;

/**
 * 获取当前登录人信息
 */
public class LoginContext {

    //获取登录信息对象 - 需要request
    public static LoginInfo getLogininfo(HttpServletRequest request){
        //1.获取token
        String token = request.getHeader("token");
        try {
            //2.获取公钥
            PublicKey publicKey;
            try (InputStream publicKeyStream = RsaUtils.class.getClassLoader().getResourceAsStream("auth_rsa_pub.txt")) {
                if (publicKeyStream == null) {
                    throw new RuntimeException("找不到密钥文件：auth_rsa_pub.txt");
                }
                publicKey = RsaUtils.getPublicKey(publicKeyStream);
            } catch (IOException e) {
                throw new RuntimeException("读取密钥失败：auth_rsa_pub.txt", e);
            }
            //需要与封装时的token版本号一致
            String version="V2.0.1";
           // PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa_pub.txt").getFile());
            //3.解密
            Payload<LoginData> payload = JwtTokenUtils.getInfoFromToken(version,token, publicKey, LoginData.class);
            //4.返回Logininfo对象
            return payload.getKernelData().getLogininfo();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}